
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%@page import="gruppe7.util.Html" %>
<%@page import="gruppe7.model.User" %>
<%@page import="gruppe7.model.Model" %>
<%@page import="gruppe7.control.ServletController" %>

<%
Html html = new Html(); 
ServletController sc = ServletController.getInstance();
User user = sc.getSession(request, response).getUser();
Model model = Model.getInstance();

out.print(html.setHeader("Show accounts")); 

%>

<script src="jquery.js"></script>

<script language="javascript">

function clearImageDiv(userId) {

	var imgDiv = $('#' + 'imgSpan_' + userId);
	imgDiv.html('');
}

function updateAccount(userId) {
	var servlet = "update_balance.do";
	var inputId = "balance_" + userId;
	var input = $("input[name="+ inputId +"]");
	var newBalance = input.val();
	var params = "userId=" + userId + "&balance=" + newBalance;

	okImage = "images/ok.png";
	errorImage = "images/error.png";

	onXML = function(xml) {
		var statusElm = $(xml).find('status');
		var hasError = $(statusElm).attr("error");
		var imgDiv = $('#' + 'imgSpan_' + userId);
		
		if (hasError == 'true') {
			imgDiv.html("<img src='images/error.png'></img>");
		}

		else {
			imgDiv.html("<img src='images/ok.png'></img>");
		}

		setTimeout('clearImageDiv(' + userId + ')', 2000);		
	}
	
	$.ajax({
		type: 'POST',
		url: servlet,
		data: params,
		dataType: 'xml',
		success: onXML
	});
}

</script>

<body>
<jsp:include page="main_links.jsp" />

<div id ='content'>
<div id='content-left'>
<h3><img src='images/tickets.png'/> Show accounts</h3><br/> 

<%
if (user.isAdminUser()) {
	
	out.println("Jeg skal vist lige rettes til<br/>");
	
	User[] users = model.getAllUsers();
	
	for (User sysUser : users) {
		int userId = sysUser.getUserID();
		float balance = sysUser.getBalance();
		String divId = "div_" + userId;
		String inputId = "balance_" + userId;
		
		%>
		<p>
		<div class="account" id="<%=divId%>">
		
		<%=sysUser.getUsername()%><br/>
		<input type="text" style="width: 75px" name="<%=inputId%>" value="<%=balance%>"></input>
		<input onclick="updateAccount('<%=userId%>')" type="button" style="width: 75px" value="Save" />
		<span id="imgSpan_<%=userId%>"></span>
		</div>
		
		<br/>
		<br/>
		
		</p>
		<%
	}
}

else {
	out.println("You have to be an administrator to use this feature");
}

%>

</div></div>

<%
out.println(html.setFooter());
%>